﻿using System;
using System.Drawing;
using System.Windows.Forms;
using org.se.fs.presenter.Library;
using org.se.fs.presenter.View;

namespace org.se.fs.view
{
    public partial class FrmSplash : Form, presenter.IView.ISplash
    {
        #region Public Property Variable
        public int ProgressBar
        {
            set
            {
                BeginInvoke(
                    (MethodInvoker)(() => pbProgressBar.Text = (value > 100 ? 100 : value).ToString()));
            }
            get { return Convert.ToInt16(pbProgressBar.Text); }
        }
        public string Status
        {
            set
            {
                BeginInvoke((MethodInvoker)(() =>
                {
                    lblStatus.Location = new Point((Width / 2) - (lblStatus.Width / 2),
                                                   lblStatus.Location.Y);
                    lblStatus.Text = value;
                }));
            }
            get { return lblStatus.Text; }
        }
        #endregion

        private readonly Splash _presenter;

        public FrmSplash()
        {
            InitializeComponent();
            _presenter = new Splash(this);
            _presenter.OnManualConfig += PresenterOnManualConfig;
            _presenter.OnNotify += PresenterOnNotify;
        }

        void PresenterOnNotify(object source, FormEvent e)
        {
            BeginInvoke((MethodInvoker)(() => Visible = false));
            var frmForm = new FrmLogin();
            frmForm.FormClosed += FrmFormFormClosed;
            frmForm.Show();
        }

        void PresenterOnManualConfig(object source, FormEvent e)
        {
            BeginInvoke((MethodInvoker)(() => Visible = false));

            do
            {
                var isConfigSuccess = FrmDatabaseConnection.FormShow();
                if (isConfigSuccess) break;
                var result =
                    MessageBox.Show(
                        @"Application will not continue unless the configuration is valid." + Environment.NewLine +
                        @"Close anyway?", @"Close application", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result.Equals(DialogResult.Yes))
                    Application.Exit();
            } while (true);
        }

        static void FrmFormFormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }

        private void TmrTimerTick(object sender, EventArgs e)
        {
            tmrTimer.Enabled = false;
        }

        private void FrmSplashLoad(object sender, EventArgs e)
        {
            tmrTimer.Enabled = true;
            _presenter.Initialize();
        }
    }
}
